<template>
  <FormView
    ref="dialog"
    embed
    :visible="visible"
    :title="
      !form.id ? (classify === '0' ? '新建入库单' : '新建冲销单') : classify === '1' ? '修改冲销单' : '修改入库单'
    "
    width="80%"
    height="500px"
    :body-padding="false"
    show-full-screen
    @close="closeDialog"
    @open="handleOpenBefore">
    <ElForm
      ref="form"
      :disabled="disabled"
      :label-position="labelPosition"
      label-width="90px"
      :model="form"
      style="height: 100%">
      <NavTabPanel>
        <ElTabPane class="my-panel" style="padding: 10px" label="基本信息">
          <ElRow>
            <ElCol :span="8">
              <ElFormItem label="入库单号" prop="caseid">
                <ElInput v-model="form.caseid" :disabled="true" />
              </ElFormItem>
            </ElCol>
            <ElCol :span="8">
              <ElFormItem label="验收订单" prop="parentCaseid">
                <ElInput v-model="form.parentCaseid" placeholder="请选择验收订单！" disabled>
                  <template #suffix>
                    <ElButton type="button" style="padding-right: 10px" @click="tableVisible = true"> 选择 </ElButton>
                  </template>
                </ElInput>
              </ElFormItem>
            </ElCol>
            <ElCol :span="8">
              <ElFormItem label="经办人">
                <ElInput v-model="form.createBy" :disabled="true" />
              </ElFormItem>
            </ElCol>
          </ElRow>
          <ElRow>
            <ElCol :span="8">
              <ElFormItem label="入库单位" prop="deptId" :rules="[{ required: true, message: '请输入入库单位！' }]">
                <FyInputTree
                  v-model="form.deptId"
                  :dic="form.dictOption.deptTreeList"
                  :props="props"
                  placeholder="选择入库单位" />
              </ElFormItem>
            </ElCol>
            <ElCol :span="8">
              <ElFormItem label="合同或发票">
                <ElSelect v-model="form.contractId" clearable placeholder="请选择合同或发票">
                  <ElOption
                    v-for="item in form.dictOption.contractTreeList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id" />
                </ElSelect>
              </ElFormItem>
            </ElCol>
            <ElCol :span="8">
              <ElFormItem label="供应商" prop="supplierId" :rules="[{ required: true, message: '请选择供应商！' }]">
                <ElSelect v-model="form.supplierId" clearable placeholder="请选择供应商">
                  <ElOption
                    v-for="item in form.dictOption.supplierTreeList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id" />
                </ElSelect>
              </ElFormItem>
            </ElCol>
          </ElRow>
          <ElRow>
            <ElCol :span="8">
              <ElFormItem
                label="入库时间"
                prop="inTime"
                style="width: 100%"
                :rules="[{ required: true, message: '请选择入库时间！' }]">
                <ElDatePicker
                  v-model="form.inTime"
                  type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  format="yyyy-MM-dd HH:mm:ss"
                  placeholder="请选择入库时间"
                  align="right" />
              </ElFormItem>
            </ElCol>
            <ElCol :span="8">
              <!-- prop="houseId" :rules="[{ required: true, message: '请选择房间名称！' }]" -->
              <ElFormItem label="房间名称">
                <FyInputTree
                  v-model="form.houseId"
                  :dic="form.dictOption.houseTreeList"
                  :props="houseProps"
                  placeholder="选择房间名称" />
              </ElFormItem>
            </ElCol>
            <ElCol :span="8">
              <ElFormItem label="存放位置">
                <!-- <ElInput v-model="form.locationId"/> -->
                <FyInputTree
                  v-model="form.locationId"
                  :dic="form.dictOption.positionTreeList"
                  :props="props"
                  placeholder="选择存放位置" />
              </ElFormItem>
            </ElCol>
          </ElRow>
          <ElRow>
            <ElCol :span="8">
              <ElFormItem label="采购方式">
                <ElSelect v-model="form.method" clearable placeholder="请选择">
                  <ElOption
                    v-for="item in form.dictOption.purchaseWayList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value" />
                </ElSelect>
              </ElFormItem>
            </ElCol>
            <ElCol :span="8">
              <ElFormItem label="货币类型">
                <ElSelect v-model="form.currencyType" clearable placeholder="请选择">
                  <ElOption
                    v-for="item in form.dictOption.currencyTypeList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value" />
                </ElSelect>
              </ElFormItem>
            </ElCol>
            <ElCol :span="8">
              <ElFormItem label="入库总金额">
                <ElInputNumber
                  v-model="form.amount"
                  disabled="disabled"
                  controls-position="right"
                  :min="0"
                  :max="9999999999999"
                  label="入库总金额" />
              </ElFormItem>
            </ElCol>
          </ElRow>
          <ElRow>
            <ElCol :span="24">
              <ElFormItem label="入库说明">
                <ElInput v-model="form.explains" type="textarea" show-word-limit row="2" autosize maxlength="2000" />
              </ElFormItem>
            </ElCol>
          </ElRow>
          <ElRow>
            <ElCol :span="24">
              <ElRow>
                <FlexRow vertical-center style="padding: 10px">
                  <ElCol :span="20">
                    <p style="padding: 0 10px">申请明细-物品列表</p>
                  </ElCol>
                  <ElButton type="primary" class="el-icon-circle-plus" @click="addCard">添加</ElButton>
                  <ElButton type="primary" class="el-icon-delete" @click="del">删除所选</ElButton>
                </FlexRow>
              </ElRow>
              <ElTable
                :data="rows"
                class="tb-edit"
                border
                :summary-method="getSummaries"
                show-summary
                style="width: 100%"
                @cell-click="cellClick"
                @selection-change="onChange">
                <ElTableColumn type="selection" width="55" />
                <ElTableColumn prop="ctiName" label="资产分类" width="120" />
                <ElTableColumn prop="name" label="资产名称" />
                <ElTableColumn prop="model" label="规格型号" width="120" />
                <ElTableColumn prop="barcode" label="条型码" width="120" />
                <ElTableColumn prop="unit" label="计量单位" width="120" />
                <ElTableColumn
                  prop="quantity"
                  :label="classify === '0' ? '*入库数量' : '*冲销数量'"
                  width="120"
                  label-class-name="quantity">
                  <template #default="scope">
                    <ElInput
                      v-if="scope.row.quantityShow"
                      v-model="scope.row.quantity"
                      @blur="loseFocus(scope.$index, scope.row, scope.column)" />
                    <span v-else style="margin-left: 10px">{{ scope.row.quantity }}</span>
                  </template>
                </ElTableColumn>
                <ElTableColumn prop="price" label="单价" width="120" />
                <ElTableColumn prop="amount" label="总价" width="120">
                  <template #default="scope">
                    <ElInput
                      v-if="scope.row.amountShow"
                      v-model="scope.row.amount"
                      @change="handleEdit(scope.$index, scope.row)"
                      @blur="loseFocusAmount(scope.$index, scope.row, scope.column)" />
                    <span v-else style="margin-left: 10px">{{ scope.row.amount }}</span>
                  </template>
                </ElTableColumn>
                <ElTableColumn prop="remarks" label="备注" width="120">
                  <template #default="scope">
                    <ElInput
                      v-if="scope.row.remarksShow"
                      v-model="scope.row.remarks"
                      @change="handleEdit(scope.$index, scope.row)"
                      @blur="loseFocusAmount(scope.$index, scope.row, scope.column)" />
                    <span v-else style="margin-left: 10px">{{ scope.row.remarks }}</span>
                  </template>
                </ElTableColumn>
              </ElTable>
            </ElCol>
          </ElRow>
          <AssetCardTable :in-type="type" :visible.sync="isPickerShow" :asset-card-id="formId" @confirm="onConfirm" />
          <SelectAcTable :visible.sync="tableVisible" @confirm="onAcList" />
        </ElTabPane>
        <ElTabPane class="my-panel" label="附件信息">
          <UploadPage ref="UploadPage" :unique-code="uniqueCode" model="purchaseOrder" classify="purchaseOrder" />
        </ElTabPane>
      </NavTabPanel>
    </ElForm>
    <template #footer>
      <ElButton type="primary" @click="dataFormSubmit">确 定</ElButton>
      <ElButton v-if="form.id > 0" type="primary" @click="warehousFinish">完成</ElButton>
      <slot name="footer"></slot>
    </template>
  </FormView>
</template>

<script>
  import { fetchList, addObj, putObj, createWarehous, edit } from '@/api/asset/warehous'
  import { delWarehousListObj } from '@/api/asset/warehouslist'

  export default {
    name: 'WarehousDialog',
    props: {
      visible: Boolean,
      formId: {
        type: String
      },
      disabled: {
        type: Boolean
      },
      classify: {
        type: String
      }
    },
    data() {
      return {
        isPickerShow: false,
        rows: [],
        uniqueCode: '',
        selectedRows: [],
        labelPosition: 'right',
        form: {
          amount: null,
          batchnumber: null,
          caseid: null,
          classify: null,
          contractId: null,
          contractName: null,
          contractNumber: null,
          createBy: '',
          createId: 3,
          createTime: '',
          currencyType: '人民币',
          deptFullname: null,
          deptId: null,
          detailed: '',
          dictOption: {
            statusList: [],
            contractTreeList: [],
            currencyTypeList: [],
            deptTreeList: [],
            houseTreeList: [],
            positionTreeList: [],
            purchaseWayList: [],
            supplierTreeList: []
          },
          explains: null,
          fullLocation: null,
          houseId: '',
          houseName: '',
          id: null,
          inTime: null,
          locationId: null,
          locationName: null,
          method: null,
          parentCaseid: null,
          parentId: null,
          status: '0',
          supplierId: null,
          supplierName: null,
          type: 'ALL',
          unid: '',
          updateBy: null,
          updateTime: null,
          acList: []
        },
        tableVisible: false,
        props: {
          value: 'id',
          label: 'name'
        },
        houseProps: {
          value: 'idCard',
          label: 'name'
        },
        type: 'ALL'
      }
    },
    watch: {},
    created() {
      this.init()
    },
    methods: {
      init() {},
      getPage(page) {
        return fetchList({ current: page.page, size: page.limit })
      },
      onConfirm(rows) {
        if (this.rows === null || this.rows.length <= 0) {
          this.rows = rows
          this.form.acList = this.rows
        } else {
          rows.forEach(row => {
            let flag = false
            this.rows.forEach(curRow => {
              if (row.sauId === curRow.sauId) {
                flag = true
              }
            })
            if (!flag) {
              this.form.acList.push(row)
            }
          })
          this.rows = this.form.acList
        }
      },
      onAcList(rows) {
        this.rows = rows
        this.form.acList = this.rows
        // this.disabled = true
        if (rows.length > 0) {
          const row = rows[0]
          this.form.parentId = row.parentId
          this.form.parentCaseid = row.parentCaseid
          this.form.batchnumber = row.batchnumber
          this.type = row.type
          this.form.type = row.type
          this.form.supplierId = row.supplierId
          this.form.supplierName = row.supplierName
          this.form.currencyType = row.currencyType
          this.form.method = row.method
          this.form.contractId = row.contractId
          this.form.contractName = row.contractName
          this.form.contractNumber = row.contractNumber
        }
      },
      onChange(rows) {
        this.selectedRows = rows
      },
      del() {
        const deleteIds = []
        this.selectedRows.forEach(row => {
          if (row.id > 0) {
            deleteIds.push(row.id)
          }
        })
        this.$confirm(`是否确认删"${deleteIds.length} "条明细数据，提示`, {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            if (deleteIds.length > 0) {
              delWarehousListObj(deleteIds)
            }
            this.rows = this.rows.filter(value => !this.selectedRows.includes(value))
            this.form.acList = this.form.acList.filter(value => !this.selectedRows.includes(value))
          })
          .then(data => {
            this.$message.success('删除成功')
          })
      },
      addCard() {
        this.isPickerShow = true
      },
      // 单击事件
      cellClick(row, column) {
        // 可编辑字段
        const showField = ['quantity', 'amount', 'remarks']
        if (showField.includes(column.property)) {
          this.$set(row, `${column.property}Show`, true)
        }
      },
      confirm() {},
      handleOpenBefore() {
        this.rows = []
        this.selectedRows = []
        if (this.formId) {
          edit(this.formId).then(response => {
            const resultObj = response.data.data
            this.form = resultObj
            this.form.unid = resultObj.unid
            this.uniqueCode = resultObj.unid
            this.type = resultObj.type
            this.rows = resultObj.acList
          })
        } else {
          // 初始化可选项。
          createWarehous(this.classify)
            .then(response => {
              const resultObj = response.data.data
              this.form = resultObj
              this.type = resultObj.type
              this.form.unid = resultObj.unid
              this.uniqueCode = resultObj.unid
            })
            .catch(() => {})
        }
      },
      dataFormSubmit() {
        this.$refs.form.validate(valid => {
          if (valid) {
            //
            if (this.rows === null || this.rows.length <= 0) {
              this.$message.warning('请选择物品列表！')
              return
            }
            if (this.rows.length > 0) {
              let checkStatus = false
              this.rows.forEach(row => {
                if (this.$isBlank(row.quantity)) {
                  checkStatus = true
                }
              })
              if (checkStatus) {
                this.$message.warning('请输入入库数量！')
                return
              }
            }
            this.form.purchaseOrderList = this.rows
            if (valid) {
              const row = this.form
              this.form.dictOption = {}
              if (row.id) {
                putObj(row).then(data => {
                  this.$message.success('修改成功')
                  this.$refs.dialog.hide()
                  this.$emit('refreshDataList')
                })
              } else {
                addObj(row).then(data => {
                  this.$message.success('添加成功')
                  this.$refs.dialog.hide()
                  this.$emit('refreshDataList')
                })
              }
            }
          }
        })
      },
      loseFocus(index, row, column) {
        const showField = ['quantity', 'amount', 'remarks']
        if (showField.includes(column.property)) {
          this.$set(row, `${column.property}Show`, false)
        }
      },
      loseFocusAmount(index, row, column) {
        const showField = ['quantity', 'amount', 'remarks']
        if (showField.includes(column.property)) {
          this.$set(row, `${column.property}Show`, false)
        }
        if (row.amount) {
          row.price = (row.amount / row.quantity).toFixed(4)
        }
      },
      closeDialog() {
        this.$refs.form.resetFields()
        this.form.deptId = -1
      },
      warehousFinish() {
        this.form.status = 3
        this.dataFormSubmit()
      },
      getSummaries(param) {
        const { columns, data } = param
        const sums = []
        const editPropertys = ['quantity', 'orderQuantity', 'amount']
        columns.forEach((column, index) => {
          if (column.property === 'unit') {
            sums[index] = '总数量'
            return
          }
          if (column.property === 'price') {
            sums[index] = '总金额'
            return
          }
          if (editPropertys.includes(column.property)) {
            const values = data.map(item => Number(item[column.property]))
            if (!values.every(value => isNaN(value))) {
              sums[index] = values.reduce((prev, curr) => {
                const value = Number(curr)
                if (!isNaN(value)) {
                  return prev + curr
                } else {
                  return prev
                }
              }, 0)
              sums[index] += ' '
            } else {
              sums[index] = '0'
            }
          }
        })
        return sums
      }
    }
  }
</script>

<style lang="scss">
  .el-table th > .cell.quantity {
    color: red;
    font-weight: normal;
    font-size: 12px;
  }
</style>
